package Kerjin.Servlet;

import java.io.IOException;
import java.util.Hashtable;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Kerjin.Util.Google.FusionTablesClient;

@SuppressWarnings("serial")
public class FusionTablesClientSample extends HttpServlet
{
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException 
	{
		StringBuffer sbMessage = new StringBuffer();
		
		try 
        {
			FusionTablesClient ftc = new FusionTablesClient();
			
			if (ftc.GetAuth("{請在此輸入帳號, ex. google.yu@gmail.com}", "請在此輸入密碼"))//取得認證
			{
				sbMessage.append(ftc.getMessage() + "<br>");
				// 資料表欄名與資料型態
				// 請自行參考 https://developers.google.com/fusiontables/docs/developers_guide?hl=zh-tw#CreatingTable
				Hashtable htabFieldInfo = new Hashtable();
				htabFieldInfo.put("FILE_BLOCK_ID", "NUMBER");
				htabFieldInfo.put("FILE_NAME", "STRING");
				htabFieldInfo.put("FILE_NAME_EXT", "STRING");
				htabFieldInfo.put("FILE_URL", "STRING");
				// 建立資料表
				String strTableID = ftc.CreateTable("test", htabFieldInfo);
				sbMessage.append("Create Table => " + ftc.getMessage() + "<br>");
				
				if (strTableID != "")
				{
					// 取得資料表機碼資訊
					sbMessage.append("<span style=\"color:#00008f\">" + ftc.GetTableShema(strTableID) + "</span><br>");
					sbMessage.append("Get Table Shema => " + ftc.getMessage() + "<br>");
					
					// 新增資料列(執行一個SQL敘述)
					sbMessage.append("<span style=\"color:#008f00\">" + ftc.ExecuteQuery("INSERT INTO " + strTableID + " ('FILE_BLOCK_ID','FILE_NAME','FILE_NAME_EXT','FILE_URL') VALUES (1,'test','.txt','http://127.0.0.1/text.txt')") + "</span><br>");
					sbMessage.append("Insert => " + ftc.getMessage() + "<br>");
					
					// 取得資料
					sbMessage.append("<span style=\"color:#008f00\">" + ftc.ExecuteQuery("SELECT * FROM " + strTableID) + "</span><br>");
					sbMessage.append("Get Data = >" + ftc.getMessage() + "<br>");
					
					// 刪除資料表
					if (ftc.DropTable(strTableID))
					{
						sbMessage.append("Drop Table => " + ftc.getMessage() + "<br>");
					}
					else
					{
						sbMessage.append("<span style=\"color:#8f0000\">error => " + ftc.getMessage() + "</span><br>");
					}
				}
			}
			else
			{
				sbMessage.append("<span style=\"color:#8f0000\">error => " + ftc.getMessage() + "</span><br>");
			}
        }
        catch (Exception exp)
        {
        	sbMessage.append(exp.getMessage());
        }
        
		resp.setContentType("text/html; charset=utf-8");
		resp.getWriter().println(sbMessage.toString());
	}
}
